Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

485
Vistas
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - How to solve it

It show error json in postman as expected but after that it crashed.

  • It not get crashed after sending success json

DB connected POST /api/signup 200 84.443 ms - 27 events.js:377 throw er; // Unhandled 'error' event ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (internal/errors.js:322:7)
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (/home/aman/Projects/Discover/discover_blog/backend/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/home/aman/Projects/Discover/discover_blog/backend/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/home/aman/Projects/Discover/discover_blog/backend/node_modules/express/lib/response.js:278:15)
at /home/aman/Projects/Discover/discover_blog/backend/controllers/auth.js:22:30
at /home/aman/Projects/Discover/discover_blog/backend/node_modules/mongoose/lib/model.js:5004:18
at processTicksAndRejections (internal/process/task_queues.js:77:11)

Emitted 'error' event on Function instance at: at /home/aman/Projects/Discover/discover_blog/backend/node_modules/mongoose/lib/model.js:5006:15 at processTicksAndRejections (internal/process/task_queues.js:77:11) { code: 'ERR_HTTP_HEADERS_SENT' }

//

const User = require("../models/user");
const shortId = require("shortid");
//
const signup = (req, res) => {
  const { name, email, password } = req.body;
  User.findOne({ email: email }).exec((err, user) => {
    if (user) {
      return res.status(400).json({
        error: "Email is taken ",
      });
    }
  });

  let username = shortId.generate();
  let profile = `${process.env.CLIENT_URL}/profile/${username}`;
  let newUser = new User({ name, email, password, profile, username });

  newUser.save((err, user) => {
    if (err) {
      return res.status(400).json({
        error: err,
      });
    }
    return res.json({
      message: "Signup is successfull! Please signin",
      user: user,
    });
  });
};

module.exports = { signup };
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You're running newUser.save too early - you need to wait until .findOne finishes, otherwise you're both sending the initial 400 status (that the email is taken) and then one with the signup results. I'd also recommend not ignoring the possible .findOne error.

const signup = (req, res) => {
    const { name, email, password } = req.body;
    User.findOne({ email: email }).exec((err, user) => {
        if (err) {
            return res.status(400).json({
                error: err,
            });
        }
        if (user) {
            return res.status(400).json({
                error: "Email is taken ",
            });
        }
        const username = shortId.generate();
        const profile = `${process.env.CLIENT_URL}/profile/${username}`;
        const newUser = new User({ name, email, password, profile, username });

        newUser.save((err, user) => {
            if (err) {
                return res.status(400).json({
                    error: err,
                });
            }
            return res.json({
                message: "Signup is successfull! Please signin",
                user: user,
            });
        });
    });
};
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda